import QtQuick
import QtQuick.Controls
import QtQuick.Layouts

import "./table.js" as Func
import "."

Item {
    id:root

    //表的列数和行数
    property int columnCount : 5
    property int rowCount : 5

    //列宽和行高
    property int cellWidth : 100
    property int cellHeight : 40

    //表的编号
    property int num : 1

    width: cellWidth * columnCount
    height: cantent.height+title.height

    Rectangle{
        id:table
        color: "transparent"

        anchors.fill: parent

        property int startIndex  // 第一个格子的索引，从0开始计数
        property int endIndex  // 最后一个格子的索引，从0开始计数
        property int selectedRows  // 第一个格子的索引，从0开始计数
        property int selectedColumns  // 最后一个格子的索引，从0开始计数
        property int selectedCount  // 选中的个数


        Rectangle{
            id:title

            height: 30
            color: "transparent"

            anchors.horizontalCenter: parent.horizontalCenter

            Label{
                id:lable

                anchors.verticalCenter: name.verticalCenter
                anchors.right: name.left

                text: "表"+root.num
                font.bold: true
                font.weight: 24
            }

            TextField{
                id:name

                anchors.horizontalCenter: parent.horizontalCenter

                font.bold: true
                font.weight: 24

                selectByMouse: true
                width: implicitWidth

                background: null
                placeholderText: "请设置表头"

                onEditingFinished: tableModel.tableTitle = text //把标题写入模型
            }
        }

        Rectangle{
            id:cantent

            width: parent.width
            height: cellHeight * rowCount

            anchors.top:title.bottom
            anchors.horizontalCenter: parent.horizontalCenter

            ListModel{
                id:tableModel

                property string tableTitle

                /*  数据结构
                    {单元格占的列个数，单元格占的行个数，单元格数据}
                    {colSpan(int),rowSpan(int),data(string),cellWidth(int),cellHeight(int)}
                */
            }

            GridLayout {
                id:gridLayout

                columnSpacing: 0
                rowSpacing: 0
                columns: root.columnCount

                anchors.fill: parent

                Repeater {
                    id:repeat

                    model:tableModel

                    Rectangle {
                        id:cell

                        property color boderColor: "#eeeeee"

                        width: model.cellWidth
                        height: model.cellHeight

                        Layout.columnSpan: model.colSpan
                        Layout.rowSpan: model.rowSpan
                        Layout.fillHeight: true
                        Layout.fillWidth: true

                        border.color: boderColor
                        border.width: 1

                        clip: true

                        TextInput {
                            id:textInput

                            anchors.fill: parent
                            horizontalAlignment: Qt.AlignHCenter
                            verticalAlignment: Qt.AlignVCenter

                            selectByMouse: true

                            text: model.data

                            //把输入的内容写道模型中
                            onTextChanged: {
                                tableModel.setProperty(index,"data",text)
                            }

                            //焦点变化清空选区
                            onFocusChanged: {
                                for(let it of Func.selectedItems)
                                {
                                    it.color = "white"
                                }

                            }

                        }

                        //调节单元格列宽大小
                        MouseArea{
                            id:rightArea

                            property point selectionStart: Qt.point(0, 0)
                            property point selectionEnd: Qt.point(0, 0)

                            height: parent.height
                            width: 5

                            anchors.right: parent.right
                            anchors.top: parent.top

                            cursorShape: Qt.OpenHandCursor

                            // 当鼠标进入区域时
                            onEntered: {
                                rightArea.cursorShape = Qt.OpenHandCursor
                            }

                            // 当鼠标离开区域时
                            onExited: {
                                rightArea.cursorShape = Qt.ArrowCursor
                            }

                            onReleased: {
                                rightArea.cursorShape = Qt.ArrowCursor

                                for(let num of Func.curItems)
                                {
                                    tableModel.setProperty(num,"cellWidth",gridLayout.children[num].width)
                                }
                                tableModel.layoutChanged()
                            }

                            onPressed: {
                                Func.curItems.clear()

                                rightArea.cursorShape = Qt.SizeHorCursor

                                if (mouse.buttons & Qt.LeftButton) {
                                    for(let i =0 ; i <tableModel.count ; ++i)
                                    {
                                        if(gridLayout.children[i].x === cell.x)
                                        {
                                            Func.curItems.add(i)
                                        }
                                    }

                                    selectionStart = mapToItem(gridLayout, mouseX, mouseY)

                                }
                            }

                            onPositionChanged: {

                                if (mouse.buttons & Qt.LeftButton) {

                                    selectionEnd = mapToItem(gridLayout, mouseX, mouseY)

                                    for(var num of Func.curItems)
                                    {
                                        gridLayout.children[num].width += selectionEnd.x - selectionStart.x
                                    }

                                    selectionStart = mapToItem(gridLayout, mouseX, mouseY)
                                }

                            }
                        }
                        //调整行高区域
                        MouseArea{
                            id:bottomArea

                            property point selectionStart: Qt.point(0, 0)
                            property point selectionEnd: Qt.point(0, 0)

                            height: 5
                            width: parent.width

                            anchors.right: parent.right
                            anchors.bottom: parent.bottom

                            cursorShape: Qt.OpenHandCursor

                            // 当鼠标进入区域时
                            onEntered: {
                                bottomArea.cursorShape = Qt.OpenHandCursor
                            }

                            // 当鼠标离开区域时
                            onExited: {
                                bottomArea.cursorShape = Qt.ArrowCursor
                            }

                            onReleased: {
                                bottomArea.cursorShape = Qt.ArrowCursor

                                for(let num of Func.curItems)
                                {
                                    tableModel.setProperty(num,"cellHeight",gridLayout.children[num].height)
                                }
                                tableModel.layoutChanged()
                            }

                            onPressed: {
                                Func.curItems.clear()

                                bottomArea.cursorShape = Qt.SizeVerCursor

                                if (mouse.buttons & Qt.LeftButton) {
                                    for(let i =0 ; i <tableModel.count ; ++i)
                                    {
                                        if(gridLayout.children[i].y === cell.y)
                                        {
                                            Func.curItems.add(i)
                                        }
                                    }

                                    selectionStart = mapToItem(gridLayout, mouseX, mouseY)
                                }
                            }

                            onPositionChanged: {

                                if (mouse.buttons & Qt.LeftButton) {

                                    selectionEnd = mapToItem(gridLayout, mouseX, mouseY)

                                    for(var num of Func.curItems)
                                    {
                                        gridLayout.children[num].height += selectionEnd.y - selectionStart.y
                                    }

                                    selectionStart = mapToItem(gridLayout, mouseX, mouseY)
                                }

                            }
                        }

                        //单元格选择区域
                        MouseArea {
                            id: selectionArea
                            width:parent.width - 10
                            height: parent.height -10

                            anchors.centerIn: parent
                            acceptedButtons: Qt.LeftButton | Qt.RightButton

                            property point selectionStart: Qt.point(0, 0) //鼠标按下的起点
                            property point selectionEnd: Qt.point(0, 0) //鼠标移动的位置

                            onClicked: {
                                textInput.focus = true
                            }

                            onPressed: {

                                //清除数据
                                Func.selectedItems.clear();

                                selectionStart = mapToItem(gridLayout, mouseX, mouseY)
                            }

                            onPositionChanged: {

                                if (mouse.buttons & Qt.RightButton) {

                                    //更新指示方块的位置和大小
                                    selectionEnd = mapToItem(gridLayout, mouseX, mouseY)
                                    selectionRectangle.visible = true

                                    selectionRectangle.x = Math.min(selectionStart.x, selectionEnd.x)
                                    selectionRectangle.y = Math.min(selectionStart.y, selectionEnd.y)

                                    selectionRectangle.width = Math.abs(selectionStart.x - selectionEnd.x)
                                    selectionRectangle.height = Math.abs(selectionStart.y - selectionEnd.y)

                                    //鼠标滑过的cell放进集合
                                    var child = gridLayout.childAt(selectionEnd.x,selectionEnd.y)
                                    if(child) Func.selectedItems.add(child)
                                }


                            }
                            onReleased: {

                                table.startIndex = -1
                                table.endIndex = -1
                                table.selectedCount = 0
                                table.selectedRows = 0
                                table.selectedColumns = 0

                                var count = Func.selectedItems.size

                                //集合中已经存在的第一个和最后一个元素
                                let firstItem = Func.selectedItems.values().next().value
                                let lastItem = [...Func.selectedItems][Func.selectedItems.size - 1]

                                if(!firstItem || !lastItem) return

                                //修改selectionRectangle范围为选中单元格的范围
                                selectionRectangle.x = firstItem.x
                                selectionRectangle.y = firstItem.y
                                selectionRectangle.width = lastItem.x - firstItem.x + lastItem.width
                                selectionRectangle.height = lastItem.y - firstItem.y + lastItem.height

                                Func.selectedItems.clear()

                                //判断selectionRectangle中有哪些子元素
                                for (var i = 0; i < tableModel.count; i++)
                                {
                                    var childItem = gridLayout.children[i]

                                    //坐标变换到selectionRectangle坐标系
                                    var child = {x:childItem.x-selectionRectangle.x , y:childItem.y-selectionRectangle.y , width:childItem.width , height:childItem.height}

                                    childItem.color = "white"

                                    //找出所有selectionRectangle范围内的元素放进集合
                                    if (selectionRectangle.contains(Qt.point(child.x, child.y)))
                                    {
                                        Func.selectedItems.add(childItem)
                                        childItem.color = "lightblue"

                                        //找到选区的第一个元素的索引
                                        table.startIndex = table.startIndex !== -1 ? table.startIndex : i

                                        //找到选区的最后一个元素的索引
                                        table.endIndex = i

                                        //计算列数
                                        if(childItem.y === firstItem.y) ++table.selectedColumns

                                        //计算行数
                                        if(childItem.x === firstItem.x) ++table.selectedRows
                                    }
                                }

                                table.selectedCount = Func.selectedItems.size

                                selectionRectangle.visible = false
                                selectionRectangle.radius = 0
                            }
                        }
                    }
                }

                //初始化啊表格
                Component.onCompleted: {
                    Func.iniTable(root.rowCount*root.columnCount,tableModel)
                }

                Rectangle {
                    id: selectionRectangle
                    color: "transparent"
                    border.color: "lightblue"
                    border.width: 1
                    visible: false

                    radius: 8
                }
            }
        }
    }

    //用于传递当前操作的组件对象到全局单例中
    MouseArea{
        anchors.fill: parent
        acceptedButtons: Qt.AllButtons  //接受所有鼠标按键的事件

        onPressed: {
            Global.curTableObj=root
            mouse.accepted = false  //鼠标事件传递给下层组件
        }
    }

    /*==================槽函数======================*/
    //合并单元格
    function onMergeCells(){

        if(!Func.selectedItems.size) return

        //处理异常情况
        if(Func.selectedItems.size !== table.selectedRows * table.selectedColumns)
        {

            Global.thowException("table","不能合并合并后的单元格请先取消合并")
            return
        }

        // console.log("pos",table.startIndex ,table.selectedCount)

        let curData = tableModel.get(table.startIndex).data

        //删除选中格子
        for(let i = 0 ; i < table.selectedRows ; ++i){

            let index = table.startIndex + root.columnCount * i - table.selectedColumns * i
            tableModel.remove(index,table.selectedColumns)
        }

        //插入一个合并后的单元格
        tableModel.insert(table.startIndex,{colSpan:table.selectedColumns,rowSpan:table.selectedRows,data:curData,cellWidth:100,cellHeight:40})

        //数据复原
        table.startIndex = 0
        table.endIndex = 0
        table.selectedCount = 0
        table.selectedColumns = 0
        table.selectedRows = 0

        Func.selectedItems.clear()
    }

    //取消合并单元格
    function onUnmergeCells(){

        if(Func.selectedItems.size !== 1) return

        let countR = tableModel.get(table.startIndex).rowSpan
        let countC = tableModel.get(table.startIndex).colSpan

        tableModel.remove(table.startIndex,1)
        console.log("click 取消合并",countR,countC,table.startIndex)

        //插入格子
        for(let j = 0 ; j < countR ; ++j)
        {
            for(let i = 0 ; i < countC ; ++i)
            {
                tableModel.insert(table.startIndex + i + j*root.columnCount,{colSpan: 1,rowSpan: 1,data:"",cellWidth:100,cellHeight:40})
            }
        }

        //数据复原
        table.startIndex = 0
        table.endIndex = 0
        table.selectedCount = 0
        table.selectedColumns = 0
        table.selectedRows = 0

        Func.selectedItems.clear()
    }

}

